<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>21绘制饼状图（面向对象）</title>
</head>
<style>
    canvas {
        border: 1px solid #ccc;
        display: block;
        margin: 100px auto;
    }
</style>
<body>
<canvas width="800" height="400"></canvas>
<script>
    var myCanvas = document.querySelector('canvas');
    var ctx = myCanvas.getContext('2d');
    /*1.绘制饼状图*/
    /*1.1根据数据绘制一个饼图*/
    /*1.2绘制标题 从扇形弧度的中心点引申一条线在这条线上划一条横线在横线上面写上标题*/
    /*1.3在画布的左上角，绘制说明 一个和扇形一样颜色的矩形 旁边就是文字说明*/

    var PieChart = function (ctx, deviationX, deviationY) {
        /*绘制工具*/
        this.ctx = ctx || document.querySelector('canvas').getContext('2d');
        /*绘制饼图的中心*/
        /*获取画布大小*/
        this.w = this.ctx.canvas.width;
        this.h = this.ctx.canvas.height;
        /*圆心的X轴偏移量*/
        this.deviationX = deviationX || 80;
        /*圆心的Y轴偏移量*/
        this.deviationY = deviationY || 30;
        /*确定饼图的中心*/
        this.x0 = this.w / 2 + this.deviationX;
        this.y0 = this.h / 2 + this.deviationY;
        /*确定饼图的半径*/
        this.radius = 125;
        /*伸出去线的长度*/
        this.outLine = 20;
        /*绘制说明矩形的大小*/
        this.rectW = 30;
        this.rectH = 16;
        /*绘制说明与canvas画布原点的间距*/
        this.spaceX = 20;
        this.spaceY = 10;
        /*矩形与文字说明之间的距离*/
        this.textIndent = 5;
    };
    PieChart.prototype.init = function (data) {
        /*1.准备数据*/
        this.drawPie(data);
    };
    PieChart.prototype.drawPie = function (data) {
        var that = this;
        /*转换成弧度*/
        var angleList = this.transformAngle(data);
        /*绘制饼图*/
        var startAngle = 0;
        angleList.forEach((item, index) => {
            /*当前结束弧度等于下一次的起始弧度*/
            var endAngle = startAngle + item.angle;
            ctx.beginPath();
            ctx.moveTo(that.x0, that.y0);
            ctx.arc(that.x0, that.y0, that.radius, startAngle, endAngle);
            var color = ctx.fillStyle = that.getRandomColor();
            ctx.fill();
            /*绘制标题*/
            that.drawTitle(startAngle, item.angle, color, item.desc);
            /*下一次要使用当前的这一次的结束弧度*/
            that.drawDesc(item.desc, index, color);
            startAngle = endAngle;
        });
    };
    /*绘制标题*/
    PieChart.prototype.drawTitle = function (startAngle, angle, color, desc) {

        /*1.确定伸出去的线，通过圆心 通过伸出去的点 确定这条线*/
        /*2.确定伸出去的点 需要确定伸出去线的长度*/
        /*3.固定伸出的线的长度*/
        /*4.计算这个点的坐标*/
        /*5.需要根据角度和斜边的长度*/
        /*5.1使用弧度 当前扇形的起始弧度+对应弧度的一半*/
        /*5.2 半径+伸出去的长度*/
        /*5.3 outX=x0+cos(angle)*(r+ outLine)*/
        /*5.4 outY=x0+sin(angle)*(r+ outLine)*/
        /*斜边*/
        var edge = this.radius + this.outLine;
        /*X轴方向直角边*/
        var edgeX = Math.cos(startAngle + angle / 2) * edge;
        /*Y轴方向直角边*/
        var edgeY = Math.sin(startAngle + angle / 2) * edge;
        /*计算出的点坐标*/
        var outX = this.x0 + edgeX;
        var outY = this.y0 + edgeY;
        // console.log(outX,outY);
        this.ctx.beginPath();
        this.ctx.moveTo(this.x0, this.y0);
        this.ctx.lineTo(outX, outY);
        this.ctx.strokeStyle = color;
        this.ctx.stroke();
        /*确定文字和下划线*/
        /*根据outX与x0的大小对线的方向进行判断*/
        /*结束点的坐标 与文字长短大小有关*/
        /*先设置文字的大小，再根据文字的长度大小来确定结束点的坐标*/
        this.ctx.font = '14px Microsoft YaHei UI';
        var textWidth = this.ctx.measureText(desc).width;
        /*文字垂直对齐方式*/
        this.ctx.textBaseline = 'bottom';
        if (outX > this.x0) {
            /*下划线在右边*/
            this.ctx.lineTo(outX + textWidth, outY);
            this.ctx.textAlign = 'left';
        } else {
            /*下划线在左边*/
            this.ctx.lineTo(outX - textWidth, outY);
            this.ctx.textAlign = 'right';
        }
        this.ctx.stroke();
        this.ctx.fillText(desc, outX, outY);
    };
    /*绘制说明*/
    PieChart.prototype.drawDesc = function (desc, index, color) {
        /*矩形的大小*/
        /*距离上和左边的间距*/
        /*矩形之间的间距*/
        this.ctx.beginPath();
        this.ctx.fillStyle = color;
        this.ctx.fillRect(this.spaceX, this.spaceY + index * (this.spaceY + this.rectH), this.rectW, this.rectH);
        /*绘制文字*/
        this.ctx.textAlign = 'left';
        this.ctx.font = '14px Microsoft YaHei UI';
        /*因为文字是以坐标点为左下角，图形是以坐标点左上角因此加一个矩形的高保证文字图形对齐*/
        this.ctx.fillText(desc, this.spaceX + this.rectW + this.textIndent, this.spaceY + this.rectH + index * (this.spaceY + this.rectH));
    };
    PieChart.prototype.transformAngle = function (data) {
        /*返回的数据内容包含弧度*/
        var total = 0;
        data.forEach((item, index) => {
            total += item.num;
        });
        /*计算弧度*/
        data.forEach((item, index) => {
            var angle = 2 * Math.PI * item.num / total;
            item.angle = angle;
        });
        return data;
    };
    /*生成随机颜色*/
    PieChart.prototype.getRandomColor = function () {
        var r = Math.floor(Math.random() * 256);
        var g = Math.floor(Math.random() * 256);
        var b = Math.floor(Math.random() * 256);
        return 'rgb(' + r + ',' + g + ',' + b + ')';
    };
    var data = [{desc: '年收入10W及以下', num: 6},
        {desc: '年收入10-15W', num: 30},
        {desc: '年收入15-20W', num: 10},
        {desc: '年收入20-25W', num: 6},
        {desc: '年收入25-30W', num: 4},
        {desc: '年收入30W以上', num: 2}];
    var pieChart = new PieChart();
    pieChart.init(data);
</script>
</body>
</html>
